//
//  HomeViewModel.swift
//  shop
//
//  Created by chen on 2025/5/13.
//

import SwiftUI

@MainActor
class HomeViewModel: ObservableObject {
    
    static let shared: HomeViewModel = HomeViewModel()
    
    public init() {}
    
    @Published var banners: [BannerData] = []
    
    @Published var makeupItems: [MakeupItemsResp] = []
    
    @Published var minId: Int64 = 1
    
    @Published var lastId: String = ""
    
    @Published var goodsResp: GoodsItemResp = GoodsItemResp()
    
    public func getMakeupItems() {
        Task{
            if minId < 0 {
                return
            }
            
            let queryParam: [String:Any] = [
                "apikey": ApiKey.haodanku.rawValue,
                "min_id": minId,
                "back": 10,
                "type": 1
            ]
            
            await NetManager.shared.httpGetList(.makeupItems, queryParam: queryParam) { (result: Result<[MakeupItemsResp]>) in
                
                if let list = result.data {
                    if self.minId == 1 {
                        self.makeupItems = list
                    } else {
                        self.makeupItems.append(contentsOf: list)
                    }
                    self.lastId = list.isEmpty ? "" : list[list.count - 1].itemid
                }
                
                self.minId = result.min_id ?? -1
            }
        }
    }
    
    public func getBanners() {
        Task{
            let queryParam: [String:Any] = [
                "version": "v1.0.0",
                "pageId": "1",
                "pageSize": 10
            ]
            
            await NetManager.shared.httpGet(.explosiveGoodsList, queryParam: queryParam) { (resp: GoodsItemResp) in
                if !resp.list.isEmpty {
                    self.banners = resp.list.reduce(into: []) { (result, item) in
                        result.append(BannerData(id: item.id, img: item.mainPic))
                    }
                }
            }
        }
    }
    
    public func getGoodsList() {
        Task{
            if goodsResp.pageId.isEmpty {
                return
            }
            
            let queryParam: [String:Any] = [
                "version": "v1.2.4",
                "pageId": goodsResp.pageId,
                "pageSize": 10
            ]
            
            await NetManager.shared.httpGet(.getGoodsList, queryParam: queryParam) { (resp: GoodsItemResp) in
                let list = resp.list
                if self.goodsResp.pageId == "1" {
                    self.goodsResp.list = list
                } else {
                    self.goodsResp.list.append(contentsOf: list)
                }
                self.lastId = list.isEmpty ? "" : list[list.count - 1].goodsId
                self.goodsResp.pageId = resp.pageId
            }
        }
    }
}

struct BannerData {
    let id: Int64
    let img: String
}
